package agenceVoyageVirtuel.server.base;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import agenceVoyageVirtuel.client.beans.AdresseData;
import agenceVoyageVirtuel.server.DB_Conn;

public class DB_Personne extends DB_Conn {
	private int chercherPersonne(AdresseData adresse) {
		String query = "SELECT idPersonne"
				+ " FROM t_personne"
				+ " WHERE prenom=" + adresse.getPersonne().getPrenom()
				+ " AND nom=" + adresse.getPersonne().getNom()
				+ ";";
	
		// prepare for rpc transport
		int id = -1;
		
		try {
			Connection connection = getConn();
			Statement select = connection.createStatement();
			ResultSet result = select.executeQuery(query);
			
			while(result.next()) {
				id = result.getInt(1); //idPersonne
				break;
			}
	
			// clean up
			result.close();
			connection.close();
		} catch(Exception e) {
			System.err.println("Mysql Statement Error: " + query);
			e.printStackTrace();
		}
	
		// return datas
		return id;		
	}
	
	public void creerPersonne(AdresseData adresse) {
		adresse.getPersonne().setIdPersonne(chercherPersonne(adresse));
		
		if(adresse.getPersonne().getIdPersonne() != -1)
			return;
		
		String query = "INSERT INTO t_personne (prenom, nom)"
				+ " VALUES (" + adresse.getPersonne().getPrenom()
				+ ", " + adresse.getPersonne().getNom()
				+ ");";
	
		try {
			Connection connection = getConn();
			PreparedStatement  prepareStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
			prepareStatement.executeUpdate();
	        ResultSet keys = prepareStatement.getGeneratedKeys();
	        
	        while(keys.next()) {
	        	adresse.getPersonne().setIdPersonne(keys.getInt(1)); //idPersonne
	        	break;
	        }
			
	        keys.close();
	        prepareStatement.close();
			connection.close();
		} catch(Exception e) {
			System.err.println("Mysql PrepareStatement Error: " + query);
			e.printStackTrace();
		}
		
		return;		
	}
}
